//
// Created by jinbang.li on 2023/6/22.
//

#include "OpEGL.h"
#include <EGL/egl.h>
#include <android/native_window.h>
#include "../Log/OpLog.h"
class COpEGL:public OpEGL{
public:
    EGLDisplay display = EGL_NO_DISPLAY;
    EGLSurface surface = EGL_NO_SURFACE;
    EGLContext context = EGL_NO_CONTEXT;
    /**
     * 1.获取EGLDisplay对象，显示设备
     * 2.初始化Display
     * 3.获取配置并创建surface
     * 4.创建并打开EGL上下文
     * @param win ndk层的窗口层
     * @return
     */
    virtual bool Init(void *win){
        ANativeWindow *nwin = (ANativeWindow *)win;
        display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
        if (display == EGL_NO_DISPLAY){
            OPLOGE("eglGetDisplay failed");
            return false;
        }


        if (eglInitialize(display,0,0) != EGL_TRUE){
            OPLOGE("eglInitialize failed");
            return false;
        }


        EGLint configSpec[] = {
                EGL_RED_SIZE,8,
                EGL_GREEN_SIZE,8,
                EGL_BLUE_SIZE,8,
                EGL_SURFACE_TYPE,EGL_WINDOW_BIT,
                EGL_NONE
        };
        EGLConfig  config = 0;
        EGLint numConfigs = 0;
        if (eglChooseConfig(display,configSpec,&config,1,&numConfigs) != EGL_TRUE){
            OPLOGE("eglChooseConfig failed");
            return false;
        }
        surface = eglCreateWindowSurface(display,config,nwin,NULL);

        const EGLint ctxAttr[] = {EGL_CONTEXT_CLIENT_VERSION,2,EGL_NONE};
        context = eglCreateContext(display,config,EGL_NO_CONTEXT,ctxAttr);
        if (context == EGL_NO_CONTEXT){
            OPLOGE("eglCreateContext failed");
            return false;
        }
        if (eglMakeCurrent(display,surface,surface,context) != EGL_TRUE){
            OPLOGE("eglMakeCurrent failed");
            return false;
        }
        return true;
    }
    virtual void Draw(){
        if (display == EGL_NO_DISPLAY || surface == EGL_NO_SURFACE){
            return;
        }
        eglSwapBuffers(display,surface);
    }
};
OpEGL *OpEGL::Get() {
     static COpEGL egl;
    return &egl;
}